<template>
  <div :class="{'filter-bar-query': showBorderBottom, 'filter-bar-border-top': showBorderTop}">
    <el-row class="system-search">
       <el-col :span="1" style="text-align: center">
        <el-button size="small" type="primary" @click="createAlarm('/alarm-create/')" class="el-icon-plus"> 新建告警</el-button>
      </el-col>
      <el-col :span="4" :offset="19">
         <el-input class="search-box" placeholder="搜索" icon="search" size="small" v-model="searchSystem" @keyup.enter.native="systemSearch"></el-input>
        <!--<el-input size="small" v-model="search"  placeholder="请输入"></el-input>-->
      </el-col>
      <!--<el-col :span="1" style="text-align: center">
        
        <el-button size="small" type="primary" @click="systemSearch">搜索</el-button>
      </el-col>-->
    </el-row>
    <template>
    <div style="margin-top:10px;">
      <div class="custom-table">
        <p class="custom-table-event">告警对象</p>
        <p class="custom-table-strategy">告警</p>
        <!--<p class="custom-table-active">操作</p>-->
      </div>
    <el-table :data="systemData" :show-header="false">
      <el-table-column prop="tree" label="告警对象">
        <template scope="scope">
          <el-tree
            :data="scope.row.treeData"
            accordion
            :highlight-current="scope.row.current"
            @node-click="sysTreeClick"
            @node-expand="sysTreeExpand"
            @node-collapse="sysTreeCollapse"
            @current-change="getTreeIndex(scope.$index)"
            :indent="30"
            :render-content="renderContent"
            default-expand-all
            >
          </el-tree>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="strategy" label="策略">
        <template scope="scope">
          <div class="sys-list" v-for="(item,index) in scope.row.treeData" :key="index">
            <div class="space-36">
              <el-tag type="primary" class="strategy-tag" v-for="(k, i) in item.systemStrategyOutput" :key="i" :closable="true" @click.native="showSysStrategy(k)" @close.stop="delSysStrategy(k.strategyCode, k.strategyName, scope.$index, scope.row, i)">{{k.strategyName}}</el-tag>
            </div>
            <div v-for="(k, i) in item.children" v-if="item.showChildren" :key="i" class="children">
              <div class="space-36">
                <el-tag type="primary" class="strategy-tag" v-for="(o, j) in k.systemStrategyOutput" :key="j" :closable="true" @click.native="showSysStrategy(o)" @close.stop="delSysStrategy(o.strategyCode, o.strategyName, scope.$index, scope.row, j)">{{o.strategyName}}</el-tag>
              </div>
              <div v-for="(m, n) in k.children" v-if="k.showChildren" :key="n">
                <div class="space-36">
                  <el-tag type="primary" class="strategy-tag" v-for="(o, j) in m.systemStrategyOutput" :key="j" :closable="true" @click.native="showSysStrategy(o)" @close.stop="delSysStrategy(o.strategyCode, o.strategyName, scope.$index, scope.row, j)">{{o.strategyName}}</el-tag>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column> -->
      <!--<el-table-column prop="action" label="操作" width="100">
        <template scope="scope">
          <div>
              <el-button type="text" @click="showStrategyList(scope.$index)">添加</el-button>
          </div>
        </template>
      </el-table-column>-->
    </el-table>
    <el-row>
      <el-col :span="4" style="margin-top: 10px;" v-if="showActiveBtn">
        <el-button size="small" @click="prev">上一步</el-button>
        <el-button size="small" type="primary" @click="next">下一步</el-button>
      </el-col>
      <el-col v-if="total > 3" :span="20" :offset="monitorPagination" class="sys-pagination">
        <el-pagination
          class="pagination"
          @current-change="sysCurrentChange"
          :current-page.sync="sysPage"
          :page-size="3"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="可用策略" :visible.sync="sysStrategyDialog" size="large" :before-close="sysStrategyDialogClose">
        <el-row>
          <el-col :span="1" style="margin-bottom: 10px;text-align:right;">
            <el-button type="primary" size="small" @click="showSysNewStrategyDialog" class="el-icon-plus"> 新建策略</el-button>
          </el-col>
          <el-col :span="4" :offset="19">
            <el-input class="search-box" placeholder="搜索" icon="search" size="small" v-model="search" @keyup.enter.native="searchStrategyName"  @click="searchStrategyName"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="font-weight: bold;">{{tips}}</el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="strategyListData"
          tooltip-effect="dark"
          @selection-change="monitorStrategyChange">
            <el-table-column type="selection" width="55" v-if="strategyListData && strategyListData.length"></el-table-column>
            <!--<el-table-column prop="strategyCode" label="编号"></el-table-column>
            <el-table-column prop="type" label="实例">
              <template scope="scope">
                {{scope.row.type === 0 ? '系统' : '探针'}}
              </template>
            </el-table-column>-->
            <el-table-column prop="strategyName" label="策略名称"></el-table-column>
            <el-table-column prop="level" label="告警级别"></el-table-column>
            <el-table-column prop="strategyDesc" label="策略描述"></el-table-column>
            <el-table-column prop="strategyCode" label="信息">
              <template scope="scope">
                <el-button type="text" @click="systemStrategyInfo(scope.row)">详细</el-button>
              </template>
            </el-table-column>
        </el-table>

        <el-row v-if="systotal > 5">
          <el-col :span="14" :offset="10" class="sys-pagination">
            <el-pagination
              class="pagination"
              @current-change="recordCurrentChange"
              :current-page.sync="recordPage"
              :page-size="5"
              layout="total, prev, pager, next"
              :total="systotal">
            </el-pagination>
          </el-col>
        </el-row>

        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="sysStrategyDialogCancel">取 消</el-button>
          <el-button type="primary" size="small" @click="rependStrategy">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="viewTitle" :visible.sync="sysNewStrategyDialog" :close-on-click-modal="false" :before-close="beforeStrategyDialogClose" :close-on-press-escape="false" :size="dialogSize">
          <router-view @dialogChange="dialogChange" @openAlarmSettings="openAlarmSettings" :req="req" :changeId="changeId"></router-view>
      </el-dialog>
      <el-dialog title="删除告警" :visible.sync="sysDelStrategyDialog">
          {{'告警名称：' + deleStrategyInfo}}
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="sysDelStrategyDialog = false">取 消</el-button>
          <el-button type="primary" :loading="delDisable" size="small" @click="delStrategy">{{ delDisable ? '' : '确 定'}}</el-button>
        </div>
      </el-dialog>
       </div>
</template>
  </div>
</template>
<script>
  import $ from 'jquery'
  import { Table, TableColumn, Row, Col, Button, Input, Message, Tree, Checkbox, CheckboxGroup, Dialog, Pagination, Tag } from 'element-ui'
  export default {
    data () {
      return {
        recordPage: 1,
        search: '',
        monitorStrategyData: [],
        systemData: [],
        strategyListData: [],
        type: '',
        code: '',
        sysStrategyDialog: false,
        treeIndex: 0,
        isIndeterminate: false,
        strategyCheckAll: '',
        strategy: [],
        strategyCodes: [],
        strategyData: [
          {
            name: '222',
            id: 222
          },
          {
            name: '333'
          }
        ],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        sysListData: [],
        sysPage: 1,
        systemLevelName: '',
        systemGroupName: '',
        systemAgentName: '',
        tips: '',
        sysNewStrategyDialog: false,
        total: 0,
        sysDelStrategyDialog: false,
        strategyCode: '',
        deleStrategyInfo: '',
        index: 0,
        localCodeData: [],
        step: 0,
        req: false,
        monitorPagination: 4,
        showActiveBtn: false,
        showBorderTop: false,
        showBorderBottom: true,
        search: '',
        notIncludeData: [],
        notInclude: '',
        searchSystem: '',
        total: 0,
        defaultExpandAll: false,
        viewTitle: '',
        dialogSize: 'large',
        changeId: false,
        showAddStrategy: false,
        systotal: 0,
        level: 0,
        pindex: 0,
        strategyListFlag: false,
        delDisable: false,
        tagStrategy: ''
      }
    },
    watch: {
      search (v) {
        !v && this._initStrategyList()
      },
      searchSystem (v) {
        !v && this._sysAgentList()
      },
      systemData: {
        deep: true,
        handler () {
          this.$forceUpdate()
        }
      }
    },
    created () {
      if (this.$route.name === 'alarm-check-instance-tree' || this.$route.name === 'check-instance-strategy-more' || this.$route.name === 'check-instance-new-strategy') {
        this.showActiveBtn = true
        this.monitorPagination = 0
        this.showBorderTop = true
        this.showBorderBottom = false
        this.$emit('changeStep', 2)
      }
      this.$root.eventBus.$on('system-or-time-change', this._sysAgentList)
      this._sysAgentList()
    },
    destroyed () {
      this.$root.eventBus.$off('system-or-time-change', this._sysAgentList)
    },
    methods: {
      systemStrategyInfo (obj) {
        this.sysStrategyDialog = false
        this.strategyListFlag = true
        this.showSysStrategy(obj)
      },
      openAlarmSettings () {
      },
      renderContent (h, { node, data, store }) {
        return (
          <span>
            <span style="display: inline-block;width: 300px;">
              <span>{data.label}</span>
            </span>
            <span>
            {data.systemStrategyOutput.map((v, j) => {
                return <span class="el-tag strategy-tag el-tag--primary" on-click={(e) => {e.stopPropagation(); this.showSysStrategy(v, data, j)}}>
                      {v.alarmName}
                    <i class="el-tag__close el-icon-close" on-click={(e) => {e.stopPropagation(); this.delSysStrategy(v.alarmCode, v.alarmName, j, data, data.index)}}></i>
                  </span>
            })}
            </span>
          </span>
        )
      },
      sysStrategyDialogCancel () {
        this.search = ''
        this.sysStrategyDialog = false
      },
      sysStrategyDialogClose (close) {
        this.search = ''
        close()
      },
      showSysStrategy (obj) {
        // this.viewTitle = '告警详情'
        this.tagStrategy = obj
        this.sysNewStrategyDialog = true
        // this.dialogSize = ''
        this.changeId = !this.changeId
        this.$router.push('/alarm/alarm-monitor/' + obj.alarmCode)
        // if (this.$route.name === 'check-instance-strategy-more' || this.$route.name === 'alarm-check-instance-tree' || this.$route.name === 'instance-new-strategy' || this.$route.name === 'check-instance-new-strategy') {
        //   this.$router.push('/alarm-create/check-instance/get/' + obj.strategyCode)
        // }
        // if (this.$route.name === 'monitor' || this.$route.name === 'monitor-strategy-more' || this.$route.name === 'monitor-new-strategy') {
        //   this.showAddStrategy = true
        //   this.$router.push('/strategy/monitor/' + obj.strategyCode)
        // }









        
      },
      async searchStrategyName () {
        if (!this.search) {
          return
        }
        var data = {
          size: 20,
          page: this.recordPage,
          name: this.search
        }
        if (this.notInclude) {
          data.notInclude = this.notInclude.substring(1)
        }
        var data = await this.api.searchStrategyName({data: data})
        this.strategyListData = data.data
      },
      sysTreeExpand (v, p, n) {
        this.systemData[this.treeIndex].current = true
        v.showChildren = true
      },
      sysTreeCollapse (v, p, n) {
        if (v.level === 1) {
          this.systemData[this.treeIndex].current = false
        }
        v.showChildren = false
      },
      async sysTreeClick (v, p, n) {
        this.notIncludeData = v.systemStrategyOutput
        this.systemData[this.treeIndex].tableData = v.systemStrategyOutput
        this.systemLevelName = ''
        this.systemGroupName = ''
        this.systemAgentName = ''
        this.tips = ''
        if (v.level == 1) {
          this.systemLevelName = p.data.label
          this.tips = this.systemLevelName
        }
        if (v.level == 2) {
          this.systemGroupName = p.data.label
          this.systemLevelName = p.parent.data.label
          this.tips =  this.systemLevelName + ' / ' + this.systemGroupName
        }
        if (v.level == 3) {
          this.systemAgentName = p.data.label
          this.systemGroupName = p.parent.data.label
          this.systemLevelName = p.parent.parent.data.label
          this.tips = this.systemLevelName + ' / ' + this.systemGroupName  + ' / ' + this.systemAgentName
        }
        if (v.id) {
          this.code = v.id
          this.systemData[this.treeIndex].showDialog = true
          // var data = await this.api.sysStrategyGetById({
          //   url: '/alarmmanage/sysStrategy/get/' + this.code
          // })
        }
        this.type = v.level
      },
      getTreeIndex (index) {
        this.treeIndex = index
        // console.log(this.treeIndex)
      },
      monitorStrategyChange (v) {
        var codes = []
        this.localCodeData = []
        v.some((v, i) => {
          this.localCodeData.push({
            strategyCode: v.strategyCode,
            strategyName: v.strategyName
          })
          codes.push(v.strategyCode)
        })
        this.strategyCodes = codes
      },
      systemSearch () {
        if (!this.searchSystem) {
          return
        }
        this._sysAgentList()
      },
      recordCurrentChange (v) {
        this.recordPage = v
        this._initStrategyList()
      },
      sysCurrentChange (v) {
        this.sysPage = v
        this._sysAgentList()
      },
      async rependStrategy () {
        if (!this.strategyCodes.length) {
          Message('请选择要添加的策略')
          return
        }
        var data = {
          code: this.code,
          strategyCodes: this.strategyCodes,
          type: this.type
        }
        this.sysStrategyDialog = false
        await this.api.sysStrategySave({data: data})
        this.localCodeData.some((v, i) => {
          this.systemData[this.treeIndex].tableData.push({
            strategyCode: v.strategyCode,
            strategyName: v.strategyName
          })
        })
        this.search = ''
        // this._sysAgentList()
      },
      showStrategyList (index) {
        if (!this.systemData[index].showDialog) {
          Message('请选择具体系统或具体业务或具体实例')
          return
        }
        // this.monitorStrategyData = data.data
        this.notInclude = ''
        if (this.notIncludeData.length > 0) {
          this.notIncludeData.some((v, i) => {
            this.notInclude += ',' + v.strategyCode
          })
        }
        this._initStrategyList()
        this.sysStrategyDialog = true
      },
      beforeStrategyDialogClose (close) {
        // if (this.$route.name !== 'check-instance-strategy-more') {
        //   if (!this.showAddStrategy) {
        //     this.sysStrategyDialog = true
        //     this._initStrategyList()
        //   }
        // }
        // if (this.strategyListFlag) {
        //   this.sysStrategyDialog = true
        // }
        close()
        this.showAddStrategy = false
        this.strategyListFlag = false
      },
      createAlarm (path) {
        // console.log(path)
        this.$router.push(path)
      },
      prev () {
        this.$emit('changeStep', 1)
        sessionStorage.removeItem('sysLevel')
        this.$router.push('/alarm-create/instance')
      },
      next () {
        this.$emit('changeStep', 3)
        this.$router.push('/alarm-create/templates')
      },
      dialogChange (v) {
        this.req = false
        if (v) {
          this.tagStrategy.alarmName = v
        }
        // this.sysStrategyDialog = true
        this.sysNewStrategyDialog = false
        // this._initStrategyList()
      },
      showSysNewStrategyDialog () {
        this.viewTitle = '新建策略'
        this.dialogSize = 'large'
        this.sysStrategyDialog = false
        this.sysNewStrategyDialog = true
        this.req = true
        if (this.$route.name === 'alarm-check-instance-tree' || this.$route.name === 'instance-new-strategy' || this.$route.name === 'check-instance-strategy-more' || this.$route.name === 'check-instance-new-strategy') {
          this.$router.push('/alarm-create/check-instance/instance-strategy')
        } else {
          this.$router.push('/strategy/monitor/new-strategy')
        }
      },
      delSysStrategy (id, info, i, row, s) {
        // this.code = row.code
        // this.type = row.level
        this.step = s
        this.index = i
        this.type = row.level
        this.deleStrategyInfo = info
        this.strategyCode = id
        this.code = row.id
        this.pindex = row.pindex
        if (row.level == 3) {
          this.treeIndex = row.ppindex
        } else if (row.level == 2) {
          this.treeIndex = row.pindex
        } else if (row.level == 1) {
          this.treeIndex = row.index
        }
        this.sysDelStrategyDialog = true
      },
      async delStrategy () {
        this.delDisable = true
        var data = {
          alarmCode: this.strategyCode
        }
        data.code = this.code
        data.type = this.type
        await this.api.delAlarmByCode({data: data})
        this.sysDelStrategyDialog = false
        if (this.type === 1) {
          this.systemData[this.treeIndex].treeData[0].systemStrategyOutput.splice(this.index, 1)
        }
        if (this.type === 2) {
          this.systemData[this.treeIndex].treeData[0].children[this.step].systemStrategyOutput.splice(this.index, 1)
        }
        if (this.type === 3) {
          this.systemData[this.treeIndex].treeData[0].children[this.pindex].children[this.step].systemStrategyOutput.splice(this.index, 1)
        }
        this.delDisable = false
        // this._sysAgentList()
      },
      async _initStrategyList () {
        var data = {
          size: 5,
          page: this.recordPage
        }
        if (this.notInclude) {
          data.notInclude = this.notInclude.substring(1)
        }
        var data = await this.api.searchStrategyName({data: data})
        this.systotal = data.total
        this.strategyListData = data.data


      },
      async _sysAgentList () {
        var sysname = false
        var data = {
          page: +(this.sysPage),
          size: 3
        }
        if (this.searchSystem || sessionStorage.getItem('curSystemName')) {
          if (sessionStorage.getItem('curSystemName') == '全部') {
            // this.defaultExpandAll = false
            // this.$forceUpdate()
          } else {
            data.name = this.searchSystem || sessionStorage.getItem('curSystemName')
            sysname = true
            // this.defaultExpandAll = true
            // this.$forceUpdate()
          }
        }
        data = await this.api.sysAgentList({data: data})
        this.systemData = []
        this.total = data.total
        if (data.success) {
          data.data.some((v, i) => {
            var sys = []
            var group = []
            if (v.groupOutput.length > 0) {
              v.groupOutput.some((k, j) => {
                var agent = []
                if (k.agentOutput && k.agentOutput.length > 0) {
                  k.agentOutput.some((u, y) => {
                    agent.push({
                      label: u.agentName + '（实例）',
                      id: u.agentCode,
                      level: 3,
                      index: y,
                      pindex: j,
                      ppindex: i,
                      systemStrategyOutput: u.systemStrategyOutput
                    })
                  })
                  group.push({
                    label: k.groupName + '（Tier）',
                    id: k.groupCode,
                    level: 2,
                    index: j,
                    pindex: i,
                    children: agent,
                    showChildren: sysname,
                    systemStrategyOutput: k.systemStrategyOutput
                  })
                } else {
                  group.push({
                    label: k.groupName + '（Tier）',
                    id: k.groupCode,
                    index: j,
                    pindex: i,
                    level: 2,
                    systemStrategyOutput: k.systemStrategyOutput
                  })
                }
              })
              sys.push({
                label: v.systemName + '（应用）',
                index: i,
                level: 1,
                id: v.systemCode,
                showChildren: sysname,
                systemStrategyOutput: v.systemStrategyOutput,
                children: group
              })
            } else {
              sys.push({
                label: v.systemName + '（应用）',
                index: i,
                level: 1,
                id: v.systemCode,
                systemStrategyOutput: v.systemStrategyOutput
              })
            }
            this.systemData.push({
              treeData: sys,
              showDialog: false,
              current: true
            })
          })
        } else {
          Message('请求失败')
        }
      }
    },
    components: {
      'el-table': Table,
      'el-table-column': TableColumn,
      'el-row': Row,
      'el-col': Col,
      'el-button': Button,
      'el-input': Input,
      'el-tree': Tree,
      'el-checkbox-group': CheckboxGroup,
      'el-checkbox': Checkbox,
      'el-dialog': Dialog,
      'el-pagination': Pagination,
      'el-tag': Tag
    }
  }
</script>
<style lang="scss">
  .system-tree, .el-tree {
    padding: 10px 0;
    border: none!important;
    background: transparent!important;
  }
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: rgb(228, 232, 241)!important;
  }
  .system-search {
    height: 40px;
  }
  .list-edit {
    color: #50bfff;
    margin-right: 8px;
    cursor: pointer;
  }
  .list-del {
    color: #ff4949;
    cursor: pointer;
  }
  .pagination {
    text-align: right;
    padding-right: 0!important;
  }
  .sys-pagination {
    margin-top: 10px;
  }
  .sys-list {
    padding: 5px;
    display: inline-block;
    cursor: pointer;
    position: relative;
  }
  .filter-bar-query {
    border-bottom: 1px solid #e5e5e5;
    padding: 0 10px;
    height: 40px;
  }
  .filter-bar-border-top {
    border-top: 1px solid #e5e5e5;
    padding: 0 10px;
    height: 40px;
    line-height: 50px;
  }
  .space-36 {
    min-height: 36px;
    padding: 1px 0;
  }
  .children {
    padding: 5px 0;
  }
  .strategy-tag {
    margin-top: 5px;
    margin-right: 5px;
  }
  .custom-table {
    background: rgb(238, 241, 246);
    color: rgb(31, 45, 61);
    height: 40px;
    line-height: 40px;
    padding: 0 18px;
    font-weight: bold;
    border-top:1px solid rgb(223, 230, 236);
    border-left:1px solid rgb(223, 230, 236);
    border-right:1px solid rgb(223, 230, 236);
    position: relative;
    p {
      float: left;
    }
    .custom-table-event {
      width: 325px;
    }
    .custom-table-active {
      width: 64px;
      padding: 0 18px;
      position: absolute;
      right: 0;
    }
  }
  .v-modal {
    z-index: 2000!important;
  }
</style>
